//
//  GHAllDiaryVC.m
//  Diary
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 王艺拓. All rights reserved.
//

#import "GHAllDiaryVC.h"
#import "GHCollectionHeaderView.h"
#import "GHBlurtView.h"
#import "GHAllDiaryCell.h"
#import "GHDiaryDataHandle.h"
#import "AppDelegate.h"

@interface GHAllDiaryVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>

@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) GHCollectionHeaderView *headerView;
@property (nonatomic, retain) GHBlurtView *blurtView;

// 背景
@property (nonatomic, retain) UIImageView *bgImageView;
@property (nonatomic, retain) GHDiaryDataHandle *dataHandle;
@property (nonatomic, retain) NSManagedObjectContext *manageContext;

// 从数据库中取出的数据
@property (nonatomic, retain) NSMutableArray *dataModelArray;

@end

@implementation GHAllDiaryVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.dataModelArray = [NSMutableArray array];
    self.dataModelArray = [self.dataHandle getImagesWithManagedObjecContext:self.manageContext];
    for (int i = 1; i <= self.dataModelArray.count; i++) {
        self.blurtView.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.8);
        self.blurtView.scrollView.backgroundColor = [UIColor clearColor];
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth * (i - 1), 10, kScreenWidth, kScreenHeight * 0.78)];
        imgView.image = self.dataModelArray[i-1];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.backgroundColor = [UIColor clearColor];
        imgView.layer.shadowOffset = CGSizeMake(10, 10);
        imgView.layer.shadowColor = [UIColor blackColor].CGColor;
        imgView.layer.shadowOpacity = 0.9;
        imgView.layer.shadowRadius = 5;
        [self.blurtView.scrollView addSubview:imgView];
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addViews];
    self.blurtView.scrollView.delegate = self;
}

- (void)addViews
{
    self.dataHandle = [[GHDiaryDataHandle alloc] init];
    
    self.bgImageView = [[UIImageView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.bgImageView.image = [UIImage imageNamed:@"baseGroundFloor"];
    self.bg_image.userInteractionEnabled = YES;
    //    self.bg_image.backgroundColor = [UIColor magentaColor];
    [self.view addSubview:_bgImageView];
    
    // 蒙层
    self.blurtView = [[GHBlurtView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    //    self.blurtView.backgroundColor = [UIColor brownColor];
    self.blurtView.pageNumber = [self.dataHandle getImagesWithManagedObjecContext:self.manageContext].count;
    //NSLog(@"self.blurtView.pageNumber = %ld" , self.blurtView.pageNumber);
    [self.view addSubview:self.blurtView];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(kScreenWidth *0.3, kScreenHeight *0.27);
    layout.minimumInteritemSpacing = kScreenWidth * 0.013;
    //NSLog(@"%f", kScreenWidth*0.3);
    layout.minimumLineSpacing = kScreenWidth * 0.02;
    layout.sectionInset = UIEdgeInsetsMake(20, 10, 30, 10);
    layout.headerReferenceSize = CGSizeMake(0,kScreenHeight * 0.15);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[GHAllDiaryCell class] forCellWithReuseIdentifier:@"RootCollectionViewCell"];
    [self.collectionView registerClass:[GHCollectionHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyHeaderView"];
    [self.view addSubview:self.collectionView];
}

- (void)setUpData
{
    self.dataModelArray = [self.dataHandle getImagesWithManagedObjecContext:self.manageContext];
    
    for (int i = 1; i <= self.dataModelArray.count; i++) {
        self.blurtView.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.8);
        self.blurtView.scrollView.backgroundColor = [UIColor clearColor];
        CGFloat makeCenterOffSet = kScreenWidth / 18;
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth * (i - 1) + makeCenterOffSet, 10, kScreenWidth - makeCenterOffSet * 2, kScreenHeight * 0.78)];
        imgView.image = self.dataModelArray[i-1];
        imgView.contentMode = UIViewContentModeScaleAspectFit;
        imgView.backgroundColor = [UIColor whiteColor];
        [self.blurtView.scrollView addSubview:imgView];
    }
}



- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [UIView animateWithDuration:0.3 animations:^{
        self.blurtView.alpha = 0;
        self.blurtView.frame = CGRectMake(0, 0, kScreenWidth*1, kScreenHeight*1.5);
        self.blurtView.scrollView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight*1.5);
        self.blurtView.bgImg.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight*1.5);
    } completion:^(BOOL finished) {
        NSArray *array = self.blurtView.scrollView.subviews;
        for (int i = 0; i < array.count; i++) {
            UIImageView *img = array[i];
            img.image= nil;
            [img removeFromSuperview];
        }
    }];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GHAllDiaryCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RootCollectionViewCell" forIndexPath:indexPath];
    cell.bg_imagV.image = self.dataModelArray[indexPath.row];
    
#pragma mark 删除Button添加点击事件和图片长按手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionLongPress:)];
    longPress.minimumPressDuration = 1.5;
    [cell.bg_imagV addGestureRecognizer:longPress];
    [cell.deleteButton addTarget:self action:@selector(actionDeleteButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteButton.tag = 100+indexPath.row;
    return cell;
}

#pragma mark 长按手势跟删除的实现
- (void)actionLongPress:(UILongPressGestureRecognizer *)sender{
    //NSLog(@"长按触发");
    for (int i = 0; i < self.dataModelArray.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        GHAllDiaryCell *cell = (GHAllDiaryCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        cell.deleteButton.frame = CGRectMake(0, 0, cell.bg_imagV.frame.size.width, cell.bg_imagV.frame.size.width);
        cell.deleteButton.center = CGPointMake(cell.bg_imagV.frame.size.width/2, cell.bg_imagV.frame.size.height/2);
        [UIView animateWithDuration:0.3 animations:^{
            cell.deleteButton.alpha = 0.5;
        }];
    }
    // 打开编辑按钮的交互
    self.headerView.editButton.userInteractionEnabled = YES;
    self.headerView.editButton.alpha = 1;
}

#pragma mark - 删除数据
- (void)actionDeleteButton:(UIButton *)sender{
    [self.dataHandle deletModelWithMnagedObjectContext:self.manageContext AndWithIndex:sender.tag-100];
    [self.dataModelArray removeObjectAtIndex:sender.tag-100];
    [self.collectionView reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self setUpData];
    [self.view bringSubviewToFront:self.blurtView];
    self.blurtView.scrollView.contentOffset = CGPointMake(kScreenWidth * indexPath.row, 0);
    [UIView animateWithDuration:0.3 animations:^{
        self.blurtView.alpha = 1;
        self.blurtView.scrollView.contentSize = CGSizeMake(kScreenWidth * self.dataModelArray.count, kScreenHeight * 0.8);
        self.blurtView.scrollView.transform = CGAffineTransformScale(self.blurtView.scrollView.transform, 1, 1);
        self.blurtView.scrollView.frame = CGRectMake(0, kScreenHeight*0.1, kScreenWidth, kScreenHeight*0.8);
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataModelArray.count;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyHeaderView" forIndexPath:indexPath];
        self.headerView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight * 0.2);
        [self.headerView.editButton addTarget:self action:@selector(actionHeadEditButton:) forControlEvents:UIControlEventTouchUpInside];
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizerAction)];
        [self.headerView addGestureRecognizer:pan];
        return _headerView;
    }
    return nil;
}

- (NSManagedObjectContext *)manageContext
{
    if (!_manageContext) {
        _manageContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
    }
    return _manageContext;
}
#pragma mark - 完成编辑
- (void)actionHeadEditButton:(UIButton *)sender{
    for (int i = 0; i < self.dataModelArray.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        GHAllDiaryCell *cell = (GHAllDiaryCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
        cell.deleteButton.frame = CGRectZero;
    }
    self.headerView.editButton.userInteractionEnabled = NO;
    self.headerView.editButton.alpha = 0;

}

#pragma mark - 平移手势，用来返回到主界面
- (void)gestureRecognizerAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma ScrollView代理方法,将提示隐藏
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [UIView animateWithDuration:0.3 animations:^{
        self.blurtView.directionLabel.alpha = 0;
    }];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
